<template>
    <div class='message-container'>
        <div class="message-wapper">

            <div class="operate-wapper">
                <div class="" style="margin-top: 10px;color: #fff;">
                    Ws-Chat
                </div>
                <div class="user" style="margin-top: 30px;">
                    <el-avatar v-if="user.id" :src="user.avatar"></el-avatar>
                    <span v-else @click="$store.state.loginVisible = true">
                        <el-avatar icon="el-icon-user-solid"></el-avatar>
                    </span>
                </div>
                <div class="icon" style="margin-top: 30px;" @click="handleClickOpearte(1)">
                    <el-badge :is-dot="showBadge" class="item">
                        <i :class="index == 1 ? 'el-icon-chat-dot-square active' : 'el-icon-chat-dot-square'"></i>
                    </el-badge>
                </div>

                <div class="icon" style="margin-top: 30px;" @click="handleClickOpearte(2)">
                    <i :class="index == 2 ? 'el-icon-user-solid active' : 'el-icon-user-solid'"></i>
                </div>
                <div class="icon" style="margin-top: 30px;" @click="handleClickOpearte(3)">
                    <el-badge :is-dot="showNoticeBadge" class="item">
                        <i :class="index == 3 ? 'el-icon-bell active' : 'el-icon-bell'"></i>
                    </el-badge>
                </div>
                <div class="icon" style="position: absolute; bottom: 50px;left: 26%;">
                    <i class="el-icon-switch-button"></i>
                </div>
            </div>

            <!-- 房间列表 -->
            <div class="left" v-if="index == 1">
                <div class="left-title">
                    聊天会话列表
                </div>
                <div :class="sessionIndex == index ? 'room session-active' : 'room'" v-for="(session, index) in sessions"
                    :key="session.id" @click="handleClikeSessionItem(index, session)">
                    <div>
                        <el-avatar :src="session.avatar"></el-avatar>
                    </div>
                    <div style="margin-left: 5px;">
                        <div class="room-name">
                            {{ session.name }}
                        </div>
                        <div class="" style="display: flex;font-size: 13px;color: #a09a9a;margin-top: 5px;">
                            <div class="room-last-message" v-html="session.lastMessage">
                            </div>
                            <!-- <div style="flex: 1;">
                                3天前
                            </div> -->
                        </div>
                    </div>
                </div>
            </div>

            <!-- 好友列表 -->
            <div class="left" v-if="index == 2">
                <div class="left-title" style="display: flex;align-items: center;">
                    <!-- <el-input v-model="input" placeholder="搜索好友"></el-input> -->
                    <i class="el-icon-circle-plus-outline" @click="$store.state.friendVisible = true"
                        style="font-size: 2rem;cursor: pointer;"></i>
                </div>
                <div class="friend" v-for="(friend, index) in friends" :key="friend.id" @click="handleClickFriend(friend)">
                    <el-avatar :src="friend.avatar"></el-avatar>
                    <div style="margin-left: 5px;">
                        {{ friend.nickname }}
                    </div>
                </div>
            </div>


            <!-- 通知消息 -->
            <div class="left" v-if="index == 3">
                <div class="left-title">
                    通知消息
                </div>
                <div v-if="notices.length">
                    <div class="notice" v-for="(notice, index) in notices" :key="notice.id">
                        <div style="display: flex;align-items: center;">
                            <el-avatar :src="notice.avatar"></el-avatar>
                            <div style="margin-left: 5px;">
                                {{ notice.nickname }}
                            </div>
                        </div>

                        <div>
                            <span v-if="notice.status == 0">
                                <span style="color: #d4152e;cursor: pointer;margin-right: 10px;"
                                    @click="handleOperApply(notice, 2)">
                                    拒绝
                                </span>
                                <span style="color: #36cc81;cursor: pointer;" @click="handleOperApply(notice, 1)">
                                    同意
                                </span>
                            </span>
                            <span v-if="notice.status == 1" style="color: #36cc81;">
                                已同意
                            </span>
                            <span v-if="notice.status == 2" style="color: #d4152e;">
                                已拒绝
                            </span>
                        </div>

                    </div>
                </div>

                <div v-else style="margin-top: 100px;color: #a09a9a;text-align: center;">
                    暂无通知消息
                </div>
            </div>

            <!-- 内容列表 -->
            <div class="center">
                <div class="room-title" v-if="choseSession">
                    {{ choseSession.name }}
                    <span style="font-size: 12px;">
                        ({{ choseSession.type == 1 ? "好友" : "群" }})
                    </span>
                </div>
                <div class="message-content-container" ref="scrollDiv">
                    <div v-for="(item, index) in messages" :key="index">
                        <div class="message-item" v-if="item.senderId != user.id">
                            <img class="message-user-avatar" :src="item.senderAvatar" alt="">
                            <div class="message-right">
                                <div class="message-user-nickname" v-if="item.isGroup !== 1">
                                    {{ item.senderNickname }}
                                </div>
                                <div class="message-item-content"
                                    style="border-radius: 2px 18px 18px;background-color: rgb(255, 223, 206);"
                                    v-html="item.content">
                                </div>
                            </div>
                        </div>
                        <div class="message-item my-message" v-else>
                            <img class="message-user-avatar" :src="user.avatar" alt="">
                            <div class="message-item-content"
                                style="border-radius: 18px 2px 18px 18px;background-color: rgb(206, 245, 255);margin-right: 5px;"
                                v-html="item.content">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="input-container">
                    <!-- <div id="im-input-box" contenteditable="true" data-placeholder="说点什么呢" class="input-wapper">

                    </div> -->
                    <el-input type="textarea" :disabled="!user.id" :autosize="{ minRows: 10, maxRows: 200 }"
                        placeholder="请输入内容" v-model="content">
                    </el-input>
                    <el-button class="sendBtn" @click="send">发 送</el-button>
                </div>
            </div>

            <!-- 音乐列表 -->
            <div class="right">
                <div class="music">
                    音乐播放列表
                </div>
                <div class="btn-audio " v-for="(music, index) in musics" :key="index">
                    <div class="cover-img" @click="audioPlay(music, index)">
                        <img :src="music.coverImg" alt="">
                        <i ref="audioItem" class="el-icon-video-play play"></i>
                        <!-- <i v-else class="el-icon-video-pause pause"></i> -->
                    </div>
                    <div style="margin-left: 5px;">
                        {{ music.name }}- {{ music.author }}
                    </div>
                </div>
                <!--音乐播放器-->
                <audio ref="audio" @ended="end" :autoplay="false" controls preload="metadata" style="display: none;">
                    您的浏览器不支持音频播放
                </audio>

            </div>


            <!-- <el-input v-model="content" placeholder="请输入内容"></el-input>
            <el-button @click="send">默认按钮</el-button> -->
        </div>

        <Login />
        <PostFriend />
    </div>
</template>
   
<script>
import { getMessageList } from '@/api/message'
import { getFriendList } from '@/api/friend'
import { getSessionList } from '@/api/session'
import { getMusicList } from '@/api/music'
import { getApplyList, updateApply } from '@/api/apply'

import Login from '@/components/modules/Login.vue'
import PostFriend from '@/components/modules/PostFriend.vue'
let socket;
export default {
    name: 'Home',
    components: {
        Login,
        PostFriend
    },
    data() {
        return {
            index: 1,
            content: "",
            messages: [],
            user: this.$store.state.user,
            messageParams: {
                pageNo: 1,
                pageSize: 10,
                receiverId: null,
                isGroup: 1
            },
            sessionParams: {
                pageNo: 1,
                pageSize: 10,
            },
            params: {
                pageNo: 1,
                pageSize: 10,
            },
            musicParams: {
                pageNo: 1,
                pageSize: 10,
            },
            friends: [],
            sessions: [],
            sessionIndex: 0,
            choseSession: null,
            audio: null,
            musics: [],
            nowMusic: null,
            isPlay: false,
            showBadge: false,
            showNoticeBadge: false,
            notices: [],
            lastPlayMusicIndex: null
        }
    },
    watch: {
        "$store.state.user": {
            deep: true,
            handler: function (newVal, oldVal) {
                this.user = newVal
                this.handleSessions()
                this.init()
            }
        }
    },
    mounted() {
        this.audio = this.$refs.audio
    },
    created() {
        getMusicList(this.musicParams).then(res => {
            this.musics = res.data.records
        })
        this.handleSessions()
        this.init()
    },
    methods: {
        handleOperApply(val, status) {
            val.status = status
            updateApply(val).then(res => {
                this.$message.success(res.message)
            }).catch(error => {
                this.$message.error(error.message)
            })
        },
        // 音频播放暂停
        audioPlay(music, index) {
            if (this.audio.src == music.url && this.isPlay) {
                this.audio.pause()
                this.isPlay = false
                this.$refs.audioItem[index].className = "el-icon-video-play play"
                return
            }
            this.audio.src = music.url
            this.audio.play()
            this.isPlay = true
            if (this.lastPlayMusicIndex != null) {
                this.$refs.audioItem[this.lastPlayMusicIndex].className = "el-icon-video-play play"
            }
            this.$refs.audioItem[index].className = "el-icon-video-pause play"
            this.lastPlayMusicIndex = index


        },
        end() {

        },
        musicInit() {
            this.audio.play()
        },
        handleClickFriend(val) {
            var domain = {
                sessionId: val.friendId,
                name: val.nickname,
                avatar: val.avatar,
                type: 1
            }
            this.choseSession = domain
            this.messages = []
            this.handleMessageList()
        },
        handleClikeSessionItem(index, val) {
            if (this.sessionIndex == index) {
                return
            }
            this.sessionIndex = index
            this.choseSession = val
            this.messages = []
            this.handleMessageList()
        },
        handleGetSessions() {
            getSessionList(this.params).then(res => {
                this.sessions = res.data.records
            })
        },
        handlegetFriendList() {
            if (!this.user.id) {
                return;
            }
            this.params.userId = this.user.id
            getFriendList(this.params).then(res => {
                this.friends = res.data.records
            })
        },
        handleClickOpearte(index) {
            if (this.index == index) {
                return;
            }
            this.index = index
            if (index == 1) {
                this.showBadge = false
                this.handleSessions()
                return
            }
            if (index == 2) {
                this.handlegetFriendList()
                return
            }
            this.showNoticeBadge = false
            this.handleGetApplyList()
        },
        handleGetApplyList() {
            this.params.userId = this.user.id
            this.params.pageNo = 1
            getApplyList(this.params).then(res => {
                this.notices = res.data.records
            }).catch(error => {
                this.$message.error(error.message)
            })
        },
        handleMessageList() {
            this.messageParams.userId = this.user.id
            this.messageParams.receiverId = this.choseSession.sessionId
            this.messageParams.isGroup = this.choseSession.type
            getMessageList(this.messageParams).then(res => {
                for (let i = res.data.records.length - 1; i >= 0; i--) {
                    this.messages.push(res.data.records[i])
                }
            })
        },
        handleSessions() {
            if (!this.user.id) {
                return;
            }
            this.sessionIndex = 0
            this.messages = []
            this.sessionParams.userId = this.user.id
            getSessionList(this.sessionParams).then(res => {
                this.sessions = res.data.records
                if (this.sessions.length > 0) {
                    this.choseSession = this.sessions[0]
                    this.handleMessageList()
                }
            })
        },
        send() {
            let message = {
                senderId: this.user.id,
                receiverId: this.choseSession.sessionId,
                content: this.content,
                isGroup: this.choseSession.type,
                senderNickname: this.user.nickname,
                senderAvatar: this.user.avatar,
                receiverAvatar: this.choseSession.avatar,
                type: 1
            }
            socket.send(JSON.stringify(message))
            this.content = ""
        },
        init() {
            let _this = this;
            if (typeof (WebSocket) == "undefined") {
                console.log("您的浏览器不支持WebSocket");
            } else {
                console.log("您的浏览器支持WebSocket");
                let socketUrl = "ws://localhost:8085/websocket/" + this.user.id;
                if (socket != null) {
                    socket.close();
                    socket = null;
                }
                // 开启一个websocket服务
                socket = new WebSocket(socketUrl);
                //打开事件
                socket.onopen = function () {
                    console.log("websocket已打开");
                };
                //  浏览器端收消息，获得从服务端发送过来的文本消息
                socket.onmessage = function (msg) {
                    console.log("收到数据====" + msg.data)
                    let message = JSON.parse(msg.data)
                    let data = JSON.parse(message.data)

                    //聊天消息
                    if (message.type == 1) {
                        if (_this.index != 1) {
                            _this.showBadge = true
                        }
                        //单聊
                        if (data.isGroup == 1 && _this.choseSession.type == 1) {
                            if ((_this.choseSession.sessionId == data.receiverId && data.senderId === _this.user.id)
                                || (_this.choseSession.sessionId == data.senderId && data.receiverId === _this.user.id)) {
                                _this.messages.push(data)
                            }
                            return
                        }
                        if (data.isGroup == 2) {
                            if (_this.choseSession.sessionId == data.receiverId) {
                                _this.messages.push(data)
                            }
                            return
                        }
                    }

                    //通知消息
                    if (message.type == 3) {
                        if (_this.index != 3) {
                            _this.showNoticeBadge = true
                        }
                        _this.notices.unshift(data)
                        console.log(data)
                        return
                    }


                };
                //关闭事件
                socket.onclose = function () {
                    console.log("websocket已关闭");
                };
                //发生了错误事件
                socket.onerror = function () {
                    console.log("websocket发生了错误");
                }
            }
        },
    },
}
</script>
   
<style scoped>
.message-container {
    display: flex;
    justify-content: center;
}

.message-wapper {
    display: flex;
    width: 60%;
    background-color: rgb(229, 229, 229);
    margin-top: 60px;

}

.operate-wapper {
    background-color: #66b1ff;
    padding: 0 10px;
    position: relative;
    text-align: center;

}

.operate-wapper .icon i {
    padding: 10px;
    border-radius: 50%;
    cursor: pointer;
}

.operate-wapper .icon .active {
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
}

.operate-wapper .icon i:hover {
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
}

.left {
    width: 20%;
    margin-right: 5px;
    background-color: rgb(243, 243, 243);
}

.left-title {
    padding: 10px 0;
    font-size: 15px;
    padding-left: 8px;
}

.room,
.friend {
    padding: 10px 0;
    background-color: #fff;
    display: flex;
    padding: 10px 10px;
    cursor: pointer;
    margin-top: 5px;
}

.session-active {
    background-color: #66b1ff6b;
}

.room:hover {
    background-color: #66b1ff6b;
}

.friend {
    align-items: center;
}

.room-last-message {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 1;
}

.notice {
    padding: 10px 0;
    background-color: #fff;
    padding: 10px 10px;
    margin-top: 5px;
}

.center {
    flex: 1;
}

.right {
    background-color: rgb(243, 243, 243);
    margin-left: 5px;
    width: 20%;
}

.music {
    padding: 10px 0;
    border-bottom: 1px solid #666;
}

.room-title {
    background-color: rgb(255, 255, 255);
    padding: 10px 0;
    border-bottom: 1px solid rgb(243, 243, 243);
    padding-left: 30px;
}

.message-content-container {
    height: 500px;
    background-color: rgb(255, 255, 255);
    border-bottom: 1px solid rgb(243, 243, 243);
    padding: 0 5px;
    overflow: auto;

}

.message-item {
    display: flex;
    padding-top: 10px;
    margin-bottom: 10px;
}

.my-message {
    flex-direction: row-reverse;
}

.message-right {
    margin-left: 10px;
}

.message-user-nickname {
    font-size: 15px;
}

.message-item-content {
    padding: 5px 5px;
    margin-top: 5px;
    max-width: 300px;
}

.message-user-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
}

.input-container {
    position: relative;
}

.sendBtn {
    position: absolute;
    right: 10px;
    bottom: 10px;
}

.input-wapper {
    border: none;
    outline: none;
    color: #fff;
    padding-left: 10px;
    height: 166px;
    padding-top: 10px;
    background-color: rgb(255, 255, 255);
}

.input-wapper:empty:before {
    content: attr(data-placeholder);
    color: #666;
}

.btn-audio {
    display: flex;
    align-items: center;
    background-color: #fff;
    padding: 5px;
}

.cover-img {
    width: 65px;
    height: 65px;
    position: relative;
}

.cover-img i {
    position: absolute;
    bottom: 5px;
    right: 5px;
    font-size: 20px;
}


.cover-img img {
    width: 100%;
    height: 100%;
}

.mp3Box {}
</style>